<template>
  <div>
    <!--      搜索框-->
    <div style="min-height: 100px;margin:0 10px; padding:10px 10px;background: white" class="search-div">
      <a-form ref="searchFormRef" name="advanced_search" class="ant-advanced-search-form"
              :model="searchFormState" @finish="searchData">
        <!--                搜索框-->
        <a-row :gutter="24">
          <!--                    <div>{{userSearchColumns}}</div>-->
          <template v-for="(searchColumnItem,index) in searchFormFields" :key="index">
            <a-col v-show="searchExpand || index <= 3" :span="6">
              <a-form-item v-if="searchColumnItem.inputType=='input'"
                           :name="searchColumnItem.key"
                           :label="searchColumnItem.title"
                           :rules="searchColumnItem.rules"
              >
                <a-input v-model:value="searchFormState[searchColumnItem.key]"
                         :placeholder="'请输入值'"></a-input>
              </a-form-item>
              <a-form-item v-if="searchColumnItem.inputType=='input-number'"
                           :name="searchColumnItem.key"
                           :label="searchColumnItem.title"
                           :rules="searchColumnItem.rules"
              >
                <a-input v-model:value="searchFormState[searchColumnItem.key]"
                         :placeholder=" '请输入值'"></a-input>
              </a-form-item>
              <a-form-item v-if="searchColumnItem.inputType=='select'"
                           :name="searchColumnItem.key"
                           :label="searchColumnItem.title"
                           :rules="searchColumnItem.rules"
              >
                <a-select
                    placeholder="请选择"
                    v-model:value="searchFormState[searchColumnItem.key]"
                    style="width: 200px"
                    :allowClear="true"
                >
                  <a-select-option v-for="{selectKey,selectName} in searchColumnItem.selectList"
                                   :value="selectKey"
                                   :key="selectKey">
                    {{ selectName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
        </a-row>
        <!--               -->
        <a-row>
          <a-col :span="24" style="text-align: right">
            <a-button type="primary" html-type="submit">搜索</a-button>
            <a-button style="margin: 0 8px" @click="() => searchFormRef.resetFields()">重置</a-button>
            <a v-if="searchFormFields.length>3" style="font-size: 12px" @click="searchExpand = !searchExpand">
              <template v-if="searchExpand">
                <UpOutlined />
                收起
              </template>
              <template v-else>
                <DownOutlined />
                展开
              </template>
            </a>
          </a-col>
        </a-row>

      </a-form>
    </div>
    <!--      表单-->
    <div class="form-div" style="margin:10px;padding:5px;background: white;">
      <!--              操作按钮-->
      <div class="button-div">
        <a-button type="primary" style="margin:0 10px" @click="showAddModal">
          新增
        </a-button>
        <a-button v-if="isVisible" class="hideButton" type="primary" @click="deleteList()">
          批量删除
        </a-button>
      </div>

      <a-table rowKey="id" :row-selection="rowSelection" :dataSource="tableDataSource"
               :columns="experimentAddTableColumns" v-model:pagination="pagination">

        <!--                    数据项-->
        <template #bodyCell="{ column,record }">
          <!--                    操作栏-->
          <template v-if="column.key === 'action'">
                          <span>
                            <a v-if="record.status !='已排课'" @click="showEditModal(record)"
                               style="color: #1677ff">修改</a>
                            <a v-else style="color: grey; cursor: not-allowed;">修改</a>
                              <a-divider type="vertical"/>
                            <a @click="deleteData(record)" style="color: red">删除</a>
                              <a-divider type="vertical"/>
                          </span>
          </template>
        </template>
      </a-table>

      <!-- 新增表单区域 -->
    </div>
    <experiment-add-model @submit-success="reloadForm" v-model:formFields="formFields" v-model:openModel="openModel"/>
    <experiment-edit-model @submit-success="reloadForm" v-model:formFields="formFields" v-model:searchFormFields="searchFormFields"
                           v-model:openModel="openEditModel" v-model:editValue="editValue"/>
  </div>


</template>
<script setup lang="ts">
import {DownOutlined, UpOutlined} from "@ant-design/icons-vue";
import {onMounted, reactive, ref} from "vue";
import {FormInstance, message, TableProps} from "ant-design-vue";
import {
  $deleteExperiment, $deleteListExperiment,
  $editExperiment,
  $getExperimentAddList
} from "@/views/experimentApplication/add/experimentAdd.api"
import {
  formFields,
  experimentAddTableColumns,
  searchFormFields
} from "@/views/experimentApplication/add/experimentAdd.data";
import ExperimentAddModel from "@/views/experimentApplication/add/experimentAddModel.vue";
import ExperimentEditModel from "@/views/experimentApplication/add/experimentEditModel.vue";

const searchFormRef = ref<FormInstance>();
const searchFormState = reactive({});
let tableDataSource = reactive([]);
const nowSelectedRows = reactive([]);
let editValue = reactive([]);
//批量删除按钮显示隐藏
const isVisible = ref(false)

//获取数据列表
onMounted(async () => {
  pagination.onChange = handlePageChang
  await reloadForm();
})

/**
 * 更换页码信息的时候显示
 * @param page
 * @param pageSize
 */
const handlePageChang = (page: any, pageSize: any) => {//参数为改变后的页码和页码数量
  pagination.current = page
  pagination.pageSize = pageSize
}


// 分页配置
const pagination = reactive({
  pageSize: 10, // 每页显示的条数
  showSizeChanger: true, // 是否可以改变每页显示的条数
  pageSizeOptions: ['10', '20', '30', '40'], // 可选的每页显示条数
  showQuickJumper: true, // 是否可以快速跳转到指定页
  showTotal: total => `共 ${total} 条`, // 显示总条数和当前数据范围
  current: 1, // 当前页数
  total: 0, // 总条数
  onChange: null // 页码改变时的回调函数,稍后才将器填充进来
})


/**
 * 更新表单函数
 * @param param
 */
const reloadForm = async () => {
  console.log("searchFormState",searchFormState);
  const {code, message: returnMessage, data} = await $getExperimentAddList(searchFormState, {
    pageNo: pagination.current,
    pageSize: pagination.pageSize
  });
  if (data != null) {
    const {records, current, total} = data
    //更新页面数据
    const totalPages = total / pagination.pageSize + 1
    if (totalPages < current) {
      pagination.current = 1
      await reloadForm()
      return //阻止执行下面代码
    }
    pagination.total = total
    // 添加新记录到响应式数组
    tableDataSource.length = 0
    console.log("records", records);
    records.forEach(record => {
      tableDataSource.push(record);
    });
  }
}
/*
监听选中数据
 */
const rowSelection: TableProps['rowSelection'] = {
  onChange: (selectedRowKeys: string[], selectedRows: any) => {
    if (selectedRowKeys.length > 1) {
      isVisible.value = true;
    } else {
      isVisible.value = false;
    }
    nowSelectedRows.length = 0;
    Object.assign(nowSelectedRows, selectedRows)
    console.log("nowSelectedRows", nowSelectedRows);
    selectedRows.forEach((selectRow) => {
          console.log("selectRow", selectRow);
        }
    )
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  },
  getCheckboxProps: (record: any) => ({
    disabled: record.name === 'Disabled User', // Column configuration not to be checked
    name: record.name,
  }),
}


// 搜索框收起
const searchExpand = ref(false);
//搜索
const searchDataSource = (values: any) => {
  reloadForm()
};

//新增
const openModel = ref(false)

const showAddModal = () => {
  openModel.value = true
}


//修改
const openEditModel = ref(false)
const showEditModal = (record: any) => {
  editValue.length = 0;
  Object.assign(editValue, record)
  console.log("editRecord", editValue);
  openEditModel.value = true
}
//删除
const deleteData = async (record: any) => {
  if (confirm('您确定要删除这个记录吗？')) {
    const id = {id: record.id}
    try {
      const result = await $deleteExperiment(id)
      const {code, message: resultMessage, data} = result
      console.log("result111", result)
      if (code == "200") {
        message.success(data)
        reloadForm();
      } else {
        message.error(resultMessage)
      }
    } catch (e) {
      message.error("删除记录失败")
    }
  } else {
    return;
  }
}

//批量删除
const deleteList = async () => {
  if (confirm('您确定要删除这批记录吗？')) {
    try {
      let list = reactive([]);
      nowSelectedRows.forEach((item: any) => {
        list.push(item.id)
      })
      const result = await $deleteListExperiment(list)
      const {code, message: resultMessage, data} = result
      if (code == "200") {
        message.success(data)
        reloadForm();
      } else {
        message.error(resultMessage)
      }
    } catch (e) {
      message.error("删除记录失败")
    }
  } else {
    return;
  }
}

const searchData=(values: any)=>{
  reloadForm();
}

</script>

<style scoped>
.hideButton {
  margin-left: 10px;
}
</style>
